<template>
  <div>
    <el-steps :active="selfApply.apply_status === undefined ? 0 : selfApply.apply_status === 0 ? 2 : 3" align-center finish-status="success" process-status="wait">
      <el-step title="Step 1" description="申请提交" />
      <el-step title="Step 2" description="申请待审核" />
      <el-step title="Step 3" description="审核完成" v-if="!selfApply.apply_status" />
      <el-step title="Step 3" description="审核批准" v-if="selfApply.apply_status === 1" />
      <el-step title="Step 3" description="审核驳回" status="error" v-if="selfApply.apply_status === 2" />
    </el-steps>

    <el-form ref="ruleFormRef" :model="roleApply" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize" status-icon>
      <el-form-item label="申请权限" prop="apply_role">
        <el-select v-model="roleApply.apply_role" placeholder="Select">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">Create</el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from '@vue/runtime-core'
import $http from '@/request/http'
import { initRoleApplyData } from '@/type/roleApply'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import emitter from '@/utils/emitter'
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    apply_role: [
        {required: true, message: '请选择', trigger: 'blur'}
    ]
})

const data = reactive(new initRoleApplyData())
const {selfApply, roleApply} = toRefs(data)

async function getSelfApply() {
  const { data: res } = await $http.get('/api/role/applylist')
  if (res.status === 1) return ElMessage.info('暂无任何申请')
  selfApply.value = res[res.length - 1]
}
onMounted(getSelfApply)

const options = [
  {
    label: '员工',
    value: 0,
  },
  {
    label: '管理员',
    value: 1,
  },
]


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async valid => {
    if (!valid) return ElMessage.error('表单验证不通过')
    const {data: res} = await $http.post('/api/role/roleapply', roleApply.value)
    if(res.status === 1) return ElMessage.error(res.message)
    ElMessage.success('申请成功')
    getSelfApply()
    emitter.emit('updCount')
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped lang="less">
.el-form {
    margin-top: 50px;
    margin-left: 150px;
}
</style>
